#include "list.h"

typedef struct _node_t {
	struct _node_t *prev;
	struct _node_t *next;
}node_t;

typedef struct _list_t {
	struct _node_t *head;
	struct _node_t *tail;
}list_t;

void list_init(void *list)
{
	((list_t *)list)->head = NULL;
    ((list_t *)list)->tail = NULL;
}

// 移出指定节点
void list_remove(void *list, void *node)
{
	if(((node_t *)node)->prev == NULL){
		((list_t *)list)->head = ((node_t *)node)->next;
	}else{
		((node_t *)node)->prev->next = ((node_t *)node)->next;
	}
	if(((node_t *)node)->next == NULL){
		((list_t *)list)->tail = ((node_t *)node)->prev;
	}else{
		((node_t *)node)->next->prev = ((node_t *)node)->prev;
	}
}

// 插入到某节点之前
void list_insert_before(void *list, void *before_node, void *new_node)
{
	if (((node_t *)before_node) == NULL){
		((node_t *)new_node)->prev = NULL;
		((node_t *)new_node)->next = NULL;
		if(((list_t *)list)->head == NULL){
			((list_t *)list)->tail = (node_t *)new_node;
		}else{
			((list_t *)list)->head->prev = (node_t *)new_node;
			((node_t *)new_node)->next = ((list_t *)list)->head;
		}
		((list_t *)list)->head = (node_t *)new_node;
	}else{
		((node_t *)new_node)->next = (node_t *)before_node;
		((node_t *)new_node)->prev = ((node_t *)before_node)->prev;
		if(((node_t *)before_node)->prev == NULL){
			((list_t *)list)->head = (node_t *)new_node;
		}else{
			((node_t *)before_node)->prev->next = (node_t *)new_node;
		}
		((node_t *)before_node)->prev = (node_t *)new_node;
	}
}

// 插入到某节点之后
void list_insert_after(void *list, void *after_node, void *new_node)
{
	if (((node_t *)after_node) == NULL){
		((node_t *)new_node)->prev = NULL;
		((node_t *)new_node)->next = NULL;
		if(((list_t *)list)->tail == NULL){
			((list_t *)list)->head = (node_t *)new_node;
		} else {
			((list_t *)list)->tail->next = (node_t *)new_node;
			((node_t *)new_node)->prev = ((list_t *)list)->tail;
		}
		((list_t *)list)->tail = (node_t *)new_node;
	} else {
		((node_t *)new_node)->prev = (node_t *)after_node;
		((node_t *)new_node)->next = ((node_t *)after_node)->next;
		if(((node_t *)after_node)->next == NULL){
			((list_t *)list)->tail = (node_t *)new_node;
		}else{
			((node_t *)after_node)->next->prev = (node_t *)new_node;
		}
		((node_t *)after_node)->next = (node_t *)new_node;
	}
}
